package com.cheng.dreams.sample.net;

import android.util.Log;

import com.cheng.dreams.sample.contract.BaseView;
import com.cheng.dreams.sample.entity.request.Request;
import com.cheng.dreams.sample.entity.response.BaseResponse;
import com.google.gson.JsonParseException;

import org.json.JSONException;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.text.ParseException;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import retrofit2.HttpException;

/**
 * CreateTime: 2016-03-30上午11:03
 * Author: wjkjinke00@126.com
 * Description:
 */
public abstract class HandleErrorObserver<T> implements Observer<T> {

    private BaseView mBaseView;
    private Request mRequest;

    public HandleErrorObserver(BaseView baseView, Request request) {
        mBaseView = baseView;
        mRequest = request;
    }


    @Override
    public void onError(Throwable e) {
        mBaseView.hideLoading();
        e.printStackTrace();
        if (e instanceof SocketTimeoutException
                || e instanceof ConnectException
                || e instanceof HttpException) {
            mBaseView.onError(-1, "网络太糟糕了!");
        } else if (e instanceof JsonParseException
                || e instanceof JSONException
                || e instanceof ParseException) {
            mBaseView.onError(-1, "服务器开小差了!");
        } else if (e instanceof ResultException) {
            ResultException resultException = (ResultException) e;
            Log.d("HandleErrorSubscriber", resultException.toString());
            mBaseView.onError(resultException.getCode(), resultException.getMessage());
        } else {
            mBaseView.onError(-1, "神秘力量导致加载数据失败!");
        }
    }


    @Override
    public void onNext(T response) {
        BaseResponse baseResponse = (BaseResponse) response;
        int code = baseResponse.getReturnCode();
        if (code == ResponseCode.SUCCESS) {
            onSuccess(response);
        } else {
            mBaseView.onError(code, baseResponse.getMsg());
        }
    }

    public abstract void onSuccess(T response);

    @Override
    public void onComplete() {
        mBaseView.hideLoading();
    }

    @Override
    public void onSubscribe(Disposable disposable) {
        if(mRequest!=null){
            mRequest.setDisposable(disposable);
        }
    }
}
